<template>
  <div>
    <Search @onSearch="handleSearch" />
    <div class="px-[30px] mt-[30px]">
      <ITable
        :list="list"
        @onAdd="handleAdd"
        @onRemove="handleRemove"
        @onAddNum="handleAddNum"
        @onDelNum="handleDelNum"
        @onUpdateNum="handleUpdateNum"
        @onBlurPrice="handleBlurNum"
      />
    </div>
    <div
      class="flex items-center justify-between mx-[30px] p-[10px] bg-[#eeecec] fixed bottom-[20px] left-0 right-0"
    >
      <div class="flex">
        <div>总商品数量: {{ total }}</div>
        <div class="ml-[50px]">总入库数量: {{ totalNum }}</div>
        <div class="ml-[50px]">总金额: {{ totalPrice }}</div>
      </div>
      <div>
        <el-button type="primary" @click="handleSave">确认入库</el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import Search from "./components/Search.vue";
import { computed, ref } from "vue";
import ITable from "./components/Table.vue";
import { mockList } from "./constants";
import rfdc from "rfdc";

const list = ref(mockList());

const total = computed(() => {
  return list.value.length;
});

const totalNum = computed(() => {
  return list.value.reduce((pre, cur) => {
    return pre + cur.inventoryNum;
  }, 0);
});

const totalPrice = computed(() => {
  return list.value.reduce((pre, cur) => {
    return pre + cur.unitPrice * cur.inventoryNum;
  }, 0);
});

function handleSearch(val) {
  const data = mockList();
  const newList = val
    ? data.filter((item) => {
        return item.name.includes(val) || item.code.includes(val);
      })
    : mockList();
  list.value = newList;
}

function handleAdd(index, row) {
  const data = rfdc()(list.value);
  data[index].add = true;
  list.value = data;
}

function handleRemove(index, row) {
  const data = rfdc()(list.value);
  data[index].add = false;
  list.value = data;
}

function handleAddNum(index, row) {
  const data = rfdc()(list.value);
  data[index].recommend.push({
    location: [],
    recommendNum: 0,
  });
  list.value = data;
}

function handleDelNum(index, row) {
  const data = rfdc()(list.value);
  data[index].recommend.pop();
  list.value = data;
}

// 输入库存单价之后计算平均价
function handleBlurNum(value, index, row, key) {
  const price = calcPrice(row);
  const data = rfdc()(list.value);
  data[index].averagePrice = price;
  list.value = data;
}
/**
 * 计算平均价格
 * （库存价*库存数量）+（入库单价*入库数量）/（库存数量+入库数量）
 */
function calcPrice(row) {
  const {
    inventoryPrice, // 库存单价
    inventoryNum, //入库数量
    storeNum, //库存数量
    unitPrice, //入库单价
  } = row;
  const avgPrice =
    (inventoryPrice * storeNum + unitPrice * inventoryNum) /
    (storeNum + inventoryNum);
  return avgPrice.toFixed(2) ?? 0;
}

function handleUpdateNum(index, row, nodeIndex) {
  const data = rfdc()(list.value);
  data[index].recommend[nodeIndex].recommendNum = 0;
  list.value = data;
}

function handleSave() {
  console.log(list.value);
}
</script>
<style></style>
